<?php

class V1 extends Controller {

	function V1()
	{
		parent::Controller();
		$this->load->library('session');
		$this->load->library('form_validation');
		$this->load->library('image_lib');
		$this->load->database('default');
		$this->load->helper(array('form', 'url'));
	}

	function signup()
	{
		//$data['title'] = 'สมัครใช้บริการ Photo Social By Location Base';
		$this->load->view('gg/signup_form');
	}

	function do_signup()
	{
		$this->form_validation->set_rules('uname', 'ชื่อเข้าใช้', 'trim|required|min_length[6]|max_length[12]|xss_clean|callback_username_check');
		$this->form_validation->set_rules('pwd', 'รหัสลับ', 'trim|required|matches[pwd2]|xss_clean');
		$this->form_validation->set_rules('pwd2', 'ยืนยันรหัสลับ', 'trim|required|xss_clean');
		$this->form_validation->set_rules('email', 'อีเมลล์', 'trim|required|valid_email|xss_clean');

		$this->form_validation->set_message('required', 'คุณยังไม่ได้กรอก %s');
		$this->form_validation->set_message('min_length', '%s ควรมีความยาวตัวอักษรไม่น้อยกว่า 6 ตัวอักษร');
		$this->form_validation->set_message('max_length', '%s ไม่ควรมีความยาวตัวอักษรมากกว่า 12 ตัวอักษร');
		$this->form_validation->set_message('matches', 'คุณกรอก %s ทั้งสองช่องไม่เหมือนกัน โปรดตรวจสอบ');
		$this->form_validation->set_message('valid_email', 'รูปแบบ %s ไม่ถูกต้อง');

		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('gg/signup_form');
		}
		else 
		{
			$username = $this->input->post('uname');
			$password = $this->input->post('pwd');
			$email = $this->input->post('email');
			$this->db->set('user_name', $username);
			$this->db->set('password', $password);
			$this->db->set('email', $email);
			$this->db->insert('member');
			$this->load->view('gg/signup_success');
		}
	}

	function username_check()
	{
		$user = $this->input->post('uname');
		$this->db->select('user_name');
		$this->db->where('user_name', $user);
		$query = $this->db->get('member');

		if($query->num_rows() > 0) {
			$this->form_validation->set_message('username_check', 'มี%sนี้อยู่ในระบบแ้ล้ว');
			return FALSE;
		} else {
			return TRUE;
		}
	}

	function authpage()
	{
		$this->load->view('gg/access_denie');
	}

	function user()
	{
		$data['sessuser'] = $this->session->userdata('username');
		$data['sessID'] = $this->session->userdata('sessID');
		$this->load->view('gg/user', $data);
	}

	function home()
	{
		/*--------------HOME----------------------------*/
		/* ข้อมูลส่วนนี้แสดงเฉพาะหน้าแรก set ค่าคงที่ไว้*/
		$data = array();
		$loc_lat = 13.762728; //พิกัด กรุงเทพฯ
		$loc_lng = 100.467224;
		
		$loc_lat = floatval($loc_lat);
		$loc_lng = floatval($loc_lng);
		$data['lat']=$loc_lat;
		$data['lng']=$loc_lng;

		$radious = 1; //กำหนดค่า radious ระยะค้นหาจากจุดศูนย์กลาง
		$lat1=$loc_lat-$radious;
		$lat2=$loc_lat+$radious;
		$lng1=$loc_lng-$radious;
		$lng2=$loc_lng+$radious;
		
		$this->db->select('*');
		$this->db->from('location');
		$this->db->where('loc_lat >= ',$lat1);
		$this->db->where('loc_lat <= ',$lat2);
		$this->db->where('loc_lng >= ',$lng1);
		$this->db->where('loc_lng <= ',$lng2);

		$data['location']=$this->db->get()->result_array();
		$data['title']='Panoramap - Photo social by location base from google map';
		$data['sessID'] = $this->session->userdata('sessID');
		$data['sessuser'] = $this->session->userdata('username');
		$data['sessuserip'] = $this->session->userdata('ip_address');
		$this->load->view('gg/home',$data);
		//------------END--HOME-----------------------------
	}

    function verifyUser()
    {
            $usermail = $this->input->post('email');
            $pwd = $this->input->post('password');
            $this->db->select('u_id, user_name, email');
			$this->db->where('email', $usermail);
            $this->db->where('password', $pwd);
            $query = $this->db->get('member');

            if($query->num_rows() > 0) 
				{
                $row = $query->row_array();	
				$sess_data = array(
					'sessID' => $this->session->userdata('session_id'),
					'userid' => $row['u_id'],
					'username' => $row['user_name'],
				);
				$this->session->set_userdata($sess_data);
				header("location:".site_url('gmap/v1/home'));
				} 
			else 
				{
					$this->session->set_flashdata('error',  'ขออภัย! ชื่อล๊อกอิน หรือ พาสเวิร์ดไม่ถูกต้อง กรุณาแก้ไขใหม่');
					header("location:".site_url('gmap/v1/home'));
				}
	}

	 function logout()
	{		
		$array_sess = array('sessID' => '', 'userid' => '', 'username' => '');
		$this->session->unset_userdata($array_sess);
		$this->session->set_flashdata('error',"You've been logged out!");
		header("location:".site_url('gmap/v1/home'));
	 }

	function getmap()
	{
		$sess_data = $this->session->userdata('sessID');
		if($sess_data == null){
		header("location:".site_url('gmap/v1/authpage')); 
		die;
		}
		
		$data['sessuser'] = $this->session->userdata('username');
		$data['title']='Panoramap - เลือกตำแหน่งบนแผนที่ของคุณ';
		$this->load->view('gg/getmap',$data);
	}

	function do_getmap()
	{
		$maplink = $this->input->post('link');
		$username = $this->session->userdata('username');
		$this->db->set('user_name', $username);
		$this->db->set('maplink', $maplink);
		$this->db->insert('umap');
		$data['maplink'] = $maplink = $this->input->post('link');
		$data['sessuser'] = $username = $this->session->userdata('username');
		$this->load->view('gg/getmap_success', $data);
	}

	function map()
	{
		$data = array();
		$loc_lat = $this->input->get('lat',true);
		$loc_lng = $this->input->get('lng',true);
		
		$loc_lat = floatval($loc_lat);
		$loc_lng = floatval($loc_lng);


		$data['title']='Your map';

		$data['lat']=$loc_lat;
		$data['lng']=$loc_lng;

		$radious = 0.2; //กำหนดค่า radious ระยะค้นหาจากจุดศูนย์กลาง
		$lat1=$loc_lat-$radious;
		$lat2=$loc_lat+$radious;
		$lng1=$loc_lng-$radious;
		$lng2=$loc_lng+$radious;
		
		$this->db->select('*');
		$this->db->from('location');
		$this->db->where('loc_lat >= ',$lat1);
		$this->db->where('loc_lat <= ',$lat2);
		$this->db->where('loc_lng >= ',$lng1);
		$this->db->where('loc_lng <= ',$lng2);

		$data['location']=$this->db->get()->result_array();
		$this->load->view('gg/map',$data);
	}

	function upload()
	{
		$sess_data = $this->session->userdata('sessID');
		if($sess_data == null){
		header("location:".site_url('gmap/v1/authpage')); 
		die;
		}

		$this->load->view('gg/upload_form', array('error' => ' ' ));
	}

	function do_upload()
	{
		$sess_data = $this->session->userdata('sessID');
		if($sess_data == null){
		header("location:".site_url('gmap/v1/authpage')); 
		die;
		}

		$this->form_validation->set_rules('loc_name', 'Location name', 'trim|required|xss_clean');
		$this->form_validation->set_rules('loc_detail','Detail','trim|required|xss_clean');
		$config['upload_path'] = '../gmap/uploads/';
		$config['allowed_types'] = 'jpg|jpeg';
		$config['max_size']	= '6144'; //kb
		$config['max_width']  = '1600';
		$config['max_height']  = '1200';		
		$this->load->library('upload', $config);
	
		if ( ! $this->upload->do_upload() and $this->form_validation->run() == FALSE)
		{
			$error = array('error' => $this->upload->display_errors());
			$this->load->view('gg/upload_form', $error);
		}	
		else
		{	
			$img_name=$this->upload->data();
			$filename = $img_name['full_path'];
			
			function ConvertFractionToDecimal($fraction)
			{
			    $result = "";
			    if (isset($fraction))
			    {
				eval ("\$result = 1.0*$fraction;");
			    }
			    return $result;
			}
			
			function ExifConvertDegMinSecToDD($deg, $min, $sec)
			{
			    $dec_min = ($min*60.0 + $sec)/60.0;
			    $result  = ($deg*60.0 + $dec_min)/60.0;
			    return $result;
			}
			
			$exif_data = array();
			$rawexif = exif_read_data($filename, 0, true);
			
			if (isset($rawexif['GPS']))
			{
				$deg = ConvertFractionToDecimal($rawexif['GPS']['GPSLatitude'][0]);
				$min = ConvertFractionToDecimal($rawexif['GPS']['GPSLatitude'][1]);
				$sec = ConvertFractionToDecimal($rawexif['GPS']['GPSLatitude'][2]);
				$exif_data['GPSLatitude'] = ExifConvertDegMinSecToDD($deg, $min, $sec);
				$exif_data['GPSLatitudeRef'] = $rawexif['GPS']['GPSLatitudeRef'];
			    
				$deg = ConvertFractionToDecimal($rawexif['GPS']['GPSLongitude'][0]);
				$min = ConvertFractionToDecimal($rawexif['GPS']['GPSLongitude'][1]);
				$sec = ConvertFractionToDecimal($rawexif['GPS']['GPSLongitude'][2]);
				$exif_data['GPSLongitude'] = ExifConvertDegMinSecToDD($deg, $min, $sec);
				$exif_data['GPSLongitudeRef'] = $rawexif['GPS']['GPSLongitudeRef'];
				    
				$Lat = $exif_data['GPSLatitude'];
				$Lng = $exif_data['GPSLongitude'];
			}
			else
			{
				$loc_name=$this->input->post('loc_name');
				$loc_name = urlencode($loc_name);
				$url='http://maps.google.com/maps/geo?q='.$loc_name.'&output=json&ie=utf8&oe=utf8&sensor=false&key=ABQIAAAA1QnAxBtPWpvkkIJ1M7uNRhSKB2H4BYfe3MAMD5ijOduM6jVyUBSbtznBSHMwaT43w3gAU97We7_oiQ&gl=th';
				$json = file_get_contents($url);
				$arr = json_decode($json);
				$Lat = $arr->Placemark[0]->Point->coordinates[1];
				$Lng = $arr->Placemark[0]->Point->coordinates[0];
			}
			
			//Insert data to database ########

			$username = $this->session->userdata('username');

			$this->db->set('loc_img',$img_name['file_name']);
			$this->db->set('user_name',$username);
			$this->db->set('loc_name',$loc_name=$this->input->post('loc_name'));
			$this->db->set('loc_detail',$loc_detail=$this->input->post('loc_detail'));
			$this->db->set('loc_lat',$Lat);
			$this->db->set('loc_lng',$Lng);
			$this->db->insert('location'); 

			//Load view #################
			$this->load->view('gg/upload_success');			
		}


	}	
}

/* End of file v1.php*/
/* Location: ./system/app_ggmap/application/controllers/v1.php */